/**
 * Created with IntelliJ IDEA.
 * User: zet
 * Date: 13-3-5
 * Time: 下午7:59
 * To change this template use File | Settings | File Templates.
 */

(function(win, doc){
    var Ads = function(el, id, adsArr){
        var that = this;
        if(typeof el === 'string'){
            el = '#' + el;
        }
        that.parent = $(el);

        //设置radio的name一致
        that.radioSet = $(el).find('input[type=radio]').attr('name', 'ads-radio-' + id);

        //设置radio的id
        that.radioSet.each(function(i, el){
            $(el).attr('id', 'ads-radio-' + id + '-' + i);
            //被点击后重设切换定时器
            el.addEventListener('click', that);
        });
        //设置label的对应id的for属性
        $(el).find('label').each(function(i, el){
            $(el).attr('for', 'ads-radio-' + id + '-' + i);
        });
        that.span1 = that.parent.find('.cr-bgimg div span:nth-child(1)');
        that.span2 = that.parent.find('.cr-bgimg div span:nth-child(2)');
        that.span3 = that.parent.find('.cr-bgimg div span:nth-child(3)');
        that.span4 = that.parent.find('.cr-bgimg div span:nth-child(4)');

        that.setImages(adsArr);
        that.resetAutoSlip();
        that.bindQrCodeBtn();
    };

    Ads.prototype = {
        handleEvent: function (e) {
            var that = this;
            switch(e.type) {
                case 'click':
                    that.resetAutoSlip();
                    break;
                default :
                    break;
            }
        },

        setImages: function(adsArr){
            if(!adsArr || !adsArr.length || adsArr.length !== 4){
                return;
            }
            this.adsArr = adsArr;
            this.span1.css('background-image', 'url(/server/' + adsArr[0].image + ')');
            this.span2.css('background-image', 'url(/server/' + adsArr[1].image + ')');
            this.span3.css('background-image', 'url(/server/' + adsArr[2].image + ')');
            this.span4.css('background-image', 'url(/server/' + adsArr[3].image + ')');
        },

        resetAutoSlip: function(){
            var that = this;
            if(that.timer) {
                clearTimeout(that.timer);
            }
            that.timer = setTimeout(function(){
                var i = that.getCurrentIndex();
                i ++;
                if(i >= 4){
                    i = 0;
                }
                that.radioSet.eq(i).click();
            }, 5000);
        },

        getCurrentIndex: function(){
            return this.parent.find('input[type=radio]:checked').index() / 2;
        },

        bindQrCodeBtn: function(){
            var that = this;
            that.parent.find('i[name=qrCodeBtn]').on('click', function(){
                var index = that.getCurrentIndex(),
                    adObj = that.adsArr[index];
                alert('打印第' + (index + 1) + '个广告， 连接为：' + adObj.link);
            });
        }
    };

    var pageCache = $('#pageCache').attr('id', null).removeClass('none');
    pageCache.parent().empty();

    var CategoryPage = function(id, categoryId){
        var that = this;
        //Name是唯一的，为了广告radio使用
        that.id = id;
        that.categoryId = categoryId;
        //父jQuery对象
        that.pageDom = pageCache.clone().attr('name', that.id).attr('forCategory', that.categoryId);
        //子Wrapper jQuery对象
        that.wrapper = that.pageDom.children('div[name=contentWrapper]');
        //子内容jQuery对象
        that.listDom = that.wrapper.children('ul[name=contentList]');
        that.lists = that.listDom.children('li');
        //子广告jQuery对象.
        that.adsWrapperDom = that.wrapper.children('section[name=contentAds]');

        //在contentList里面可插入li的index列表
        that.availArray = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 30, 31, 32, 33, 34, 35];

        //当前下一个li插入的index
        that.insertIndex = 0;

        //已经插入的li的数目
        that.length = 0;
    };

    CategoryPage.prototype = {
        insert: function(goodsObj){
            if(!this.couldInsert()){
                return;
            }

            var li = this.lists.eq(this.availArray[this.insertIndex])
                .attr('goodsId', goodsObj.id)
                .on('click', function(){
                    var that = $(this),
                        goodsId = that.attr('goodsId');

                    var src = that.find('img').attr('src');
                    var pos = that.offset();
                    var targetTop = orderBtn.offset().top;
                    goodsAddAnimationImg.attr('src', src);
                    goodsAddAnimation.css({'top': pos.top, 'left': pos.left, 'width': '180px', 'height': '250px'}).show()
                        .animate({'top': targetTop, 'left': '0', width: '20px', height: '20px'}, 700, function(){
                            $(this).hide();
                            OrderManager.addGoods(goodsId);
                        });
                });

            li.find('img').attr('src', '/server/' + goodsObj.minImagePath);
            li.find('div.price').removeClass('none').find('span[name=priceNumber]').text(parseFloat(goodsObj.price).toFixed(1));
            this.insertIndex ++;
            this.length ++;
        },

        couldInsert: function(){
            return this.length < this.availArray.length;
        },

        initAds: function(imgArr){
            var that = this;
            if(!that.ads){
                that.ads = new Ads(that.adsWrapperDom, that.id, imgArr);
            }
            else {
                that.ads.setImages(imgArr)
            }
        }
    };


    var orderScroller = null,

        mainScroller = new iScroll('wrapper', {
            snap: true,
            vScroll: false,
            hScrollbar: false,
            vScrollbar: false,
            momentum: false
        }),


        categoryTree = new Array(),
        categoryMap = {},            //根据id的Category索引
        goodsMap = {},              //根据id的Goods索引
        categoryPageMap = {},       //根据id的Category Pages的索引
        pagesArray = new Array(),   //所有的page的数组，用于更新广告
        AdsObjArray = null,

        mask = $('#mask'),

        orderBtn = $('#orderBtn'),
        orderWrapper = $('#orderWrapper'),
        orderCloseBtn = $('#orderCloseBtn'),
        orderList = $('#orderList'),
        orderLi = orderList.find('#orderLi').attr('id', null).remove(),
        orderCount = $('#orderCount'),
        orderConfirmBtn = orderWrapper.find('#orderConfirmBtn'),
        emptyOrder = orderWrapper.find('#emptyOrder'),

        OrderManager = {
            list: orderList,
            liCache: orderLi,
            orderTotalPrice: orderWrapper.find('span[name=orderTotalPrice]'),
            orderCount: 0,

            orderMap: {},   //key = goodsId, value = count
            domMap: {},     //key = goodsId, value = the li dom

            //增加一个商品
            addGoods: function(goodsId){
                var goods = goodsMap[goodsId], theDom;
                if(this.orderMap[goodsId]){
                    var priceDom, countDom;
                    this.orderMap[goodsId] = this.orderMap[goodsId] + 1;
                    theDom = this.domMap[goodsId];
                    countDom = theDom.find('div[name=count]');
                    priceDom = theDom.find('div[name=totalPrice]');

                    countDom.text(parseInt(countDom.text()) + 1);
                    priceDom.text((parseFloat(priceDom.text()) + goods.price).toFixed(1));
                }
                else {
                    this.orderMap[goodsId] = 1;
                    theDom = this.domMap[goodsId] = this.liCache.clone();
                    theDom.attr('goodsId', goods.id);
                    theDom.find('img[name=goodsPic]').attr('src', '/server/' + goods.minImagePath);
                    theDom.find('div[name=goodsTitle]').text(goods.name);
                    theDom.find('div[name=count]').text(1);
                    theDom.find('div[name=totalPrice]').text(goods.price.toFixed(1));

                    theDom.find('div[name=addBtn]').on('click', orderLiAddBtnFn);
                    theDom.find('div[name=minusBtn]').on('click', orderLiMinusFn);
                    theDom.find('i[name=deleteBtn]').on('click', orderDeleteBtnFn);
                    this.list.append(theDom);
                }
                this.updateTotalPrice();
                this.updateCount();
            },

            //减少一个商品
            minusGoods: function(goodsId){
                var goods = goodsMap[goodsId], theDom;
                if(this.orderMap[goodsId]){
                    if(this.orderMap[goodsId] === 1){
                        this.deleteGoods(goodsId);
                    }
                    else {
                        var priceDom, countDom;
                        this.orderMap[goodsId] = this.orderMap[goodsId] - 1;
                        theDom = this.domMap[goodsId];
                        countDom = theDom.find('div[name=count]');
                        priceDom = theDom.find('div[name=totalPrice]');

                        countDom.text(parseInt(countDom.text()) -1);
                        priceDom.text((parseFloat(priceDom.text()) - goods.price).toFixed(1));
                    }
                }
                this.updateTotalPrice();
                this.updateCount();
            },

            //删除一个商品
            deleteGoods: function(goodsId){
                this.domMap[goodsId].hide(300, function(){
                    $(this).remove();
                    orderScroller.refresh();
                });
                delete this.orderMap[goodsId];
                delete this.domMap[goodsId];
                this.updateTotalPrice();
                this.updateCount();
            },

            //重新计算总价
            updateTotalPrice: function(){
                var goodsId, count, goods, total = 0;
                for(goodsId in this.orderMap){
                    goods = goodsMap[goodsId];
                    count = this.orderMap[goodsId];
                    total += goods.price * count;
                }
                this.orderTotalPrice.text(total.toFixed(1));
            },

            updateCount: function(){
                var goodsId, count, total = 0;
                for(goodsId in this.orderMap){
                    count = this.orderMap[goodsId];
                    total += count;
                }
                this.orderCount = total;
                orderCount.text(total);
            },

            commitOrder: function(){
                var goodsIds = new Array(),
                    types = new Array(),
                    counts = new Array(),
                    prices = new Array(),

                    goodsId, count, goods, total = 0;
                for(goodsId in this.orderMap){

                    goods = goodsMap[goodsId];
                    count = this.orderMap[goodsId];
                    total += goods.price * count;

                    goodsIds.push(goodsId);
                    types.push('默认');
                    counts.push(count);
                    prices.push(goods.price);
                }

                var obj = {
                    shopperId : 1,
                    customId : 1,
                    machineId : 1,
                    totalPrice : total,
                    itemBuyGoodsIds : goodsIds,
                    itemBuyTypes : types,
                    itemBuyCounts : counts,
                    itemBuyPrices : prices
                },
                    that = this;

                var params = decodeURIComponent($.param(obj, true));
                $.ajax({
                    type: "post",
                    data: params,
                    url: "/server/ajax/buyGoods.htm",
                    beforeSend: function(XMLHttpRequest){

                    },
                    success: function(data, textStatus){
                        if(data.id){
                            alert('订单成功，订单号为:' + data.orderNum);
                            that.empty();
                            closeOrderWrapper();
                        }
                    }
                });
            },

            empty: function(){
                var goodsId;
                for(goodsId in this.orderMap){
                    this.domMap[goodsId].remove();
                }
                this.orderMap = {};
                this.domMap = {};
                this.updateCount();
                this.updateTotalPrice();
            }
        },

        orderLiAddBtnFn = function(){
            var that = this,
                goodsId = $(that).closest('li[name=orderLi]').attr('goodsId');
            OrderManager.addGoods(goodsId);
            orderScroller.refresh();
        },

        orderLiMinusFn = function(){
            var that = this,
                goodsId = $(that).closest('li[name=orderLi]').attr('goodsId');
            OrderManager.minusGoods(goodsId);
            orderScroller.refresh();
        },

        orderDeleteBtnFn = function(){
            var that = this,
                goodsId = $(that).closest('li[name=orderLi]').attr('goodsId');
            OrderManager.deleteGoods(goodsId);
            orderScroller.refresh();
        },

        goodsAddAnimation = $('#goodsAddAnimation'),
        goodsAddAnimationImg = goodsAddAnimation.find('img'),

        categoryBtn = $('#categoryBtn'),
        categoryWrapper = $('#categoryWrapper'),
        categoryList = $('#categoryList'),
        categoryItem = $('#categoryItem').attr('id', null),
        categoryAllBtn = $('#categoryAllBtn'),

        //开启订单详情窗口
        showOrderWrapper = function(){
            categoryWrapper.hide();
            mask.show();
            orderWrapper.show(500, function(){
                if(!orderScroller){
                    orderScroller = new iScroll('orderListWrapper', {
                        hScroll: false,
                        hScrollbar: false
                    })
                }
                orderScroller.refresh();
            });
        },

        //关闭订单详情窗口
        closeOrderWrapper = function(){
            orderWrapper.hide(500, function(){
                mask.hide();
            });
        },

        //开启类别选择窗口
        showCategoryWrapper = function(){
            categoryBtn.addClass('checked');
            categoryWrapper.show(500);
        },

        //关闭类别选择窗口
        closeCategoryWrapper = function(){
            categoryBtn.removeClass('checked');
            categoryWrapper.hide(500);
        },

        //类别选择函数
        categoryItemClickFn = function(){
            var that = this,
                categoryId = $(that).addClass('checked').attr('category-id');
            $(that).siblings().removeClass('checked');
            closeCategoryWrapper();
            showPagesByCategoryId(categoryId);
        },

        //id代表category的id，
        //name ： category显示的名字
        //isChild:  是否是子category
        addCategoryItem = function(id, name, isChildren){
            //dom添加
            var categoryDom = categoryItem.clone().attr('category-id', id).text(name)
                .on('click', categoryItemClickFn);
            if(isChildren){
                categoryDom.addClass('children');
            }
            categoryList.append(categoryDom);
        },

        getGoodsByCategory = function(categoryId){
            $.ajax({
                url: 'http://192.168.1.106:8080/server/ajax/query/queryCategoryGoods.htm?shopperId=1&categoryId=' + categoryId,
                dataType: 'json',
                type: 'get',
                success: function(data){
                    //console.dir(data);
                    insertGoodsToPage(categoryId, data);
                },
                fail: function(a, b){
                    console.log(b);
                },
                async: false
            });
        },
        getAllGoods = function(){
            $.ajax({
                url: 'http://192.168.1.106:8080/server/ajax/query/queryShopGoods.htm?shopperId=1',
                dataType: 'json',
                type: 'get',
                success: function(data){
                    insertGoodsToPage('all', data);
                    showPagesByCategoryId('all');
                },
                fail: function(a, b){
                    console.log(b);
                },
                async: false
            });
        },

        pageList = $('#pageList'),
        insertGoodsToPage = function(categoryId, goodsArray){
            var length = 0, i, pages, currentPage;
            if(!categoryPageMap[categoryId]){
                categoryPageMap[categoryId] = new Array();
                length = categoryPageMap[categoryId].length;
                categoryPageMap[categoryId].push(new CategoryPage('category-' + categoryId + '-index-' + length, categoryId));
            }
            pages = categoryPageMap[categoryId];
            length = pages.length;
            currentPage = pages[length -1];
            for(i = 0; i < goodsArray.length; i ++){
                if(!currentPage.couldInsert()) {
                    pages.push(new CategoryPage('category-' + categoryId + '-index-' + length, categoryId));
                    length = pages.length;
                    currentPage = pages[length -1];
                }
                currentPage.insert(goodsArray[i]);
                if(!goodsMap[goodsArray[i].id]){
                    goodsMap[goodsArray[i].id] = goodsArray[i];
                }
            }
            for(i = 0; i < pages.length; i ++){
                pagesArray.push(pages[i]);
                pageList.append(pages[i].pageDom);
            }
        },

        showPagesByCategoryId = function(id){
            var i, showPages;
            for(i = 0; i < pagesArray.length; i ++){
                pagesArray[i].pageDom.addClass('none');
            }
            showPages = categoryPageMap[id];
            if(!showPages){
                return;
            }
            for(i = 0; i < showPages.length; i++){
                showPages[i].pageDom.removeClass('none');
            }
            pageList.width((showPages.length * 1800 + 20) + 'px');
            mainScroller.refresh();
        },

        refreshAds = function(){
            $.ajax({
                url: 'http://192.168.1.106:8080/server/ajax/query/queryAdvertisements.htm?shopperId=1&machieId=1&position=1&ranking=4',
                type: 'get',
                dataType: 'json',
                success: function(data){
                    AdsObjArray = data;
                    var i, temp;
                    for(i = 0; i < pagesArray.length; i++){
                        temp = pagesArray[i];
                        temp.initAds(data);
                    }
                },
                fail: function(a, b){
                    console.log(b);
                }
            });
        },

        getCategory = function(){
            $.ajax({
                url: 'http://192.168.1.106:8080/server/ajax/query/queryCategories.htm?shopperId=1',
                dataType: 'json',
                type: 'get',
                success: function(data){
                    console.dir(data);
                    categoryTree = data;
                    var i, j, arr1, item1, arr2, item2;
                    //遍历父类
                    for(i = 0; i < data.length; i ++){
                        item1 = data[i];

                        //dom添加
                        addCategoryItem(item1.id, item1.name);
                        getGoodsByCategory(item1.id);
                        arr1 = new Array();
                        arr1.push(item1.id);
                        if(item1.children){
                            //遍历子类
                            for(j = 0; j < item1.children.length; j ++){
                                item2 = item1.children[j];
                                arr2 = new Array();
                                arr2.push(item2.id);
                                arr1.push(item2.id);
                                categoryMap[item2.id] = arr2;

                                addCategoryItem(item2.id, item2.name, true);
                                getGoodsByCategory(item2.id);
                            }
                        }
                        categoryMap[item1.id] = arr1;
                    }
                },
                error: function(a, b){
                    console.log(b);
                },
                async: false
            });
        };

    getCategory();
    getAllGoods();
    refreshAds();

    categoryAllBtn.on('click', categoryItemClickFn);

    /* 绑定按钮事件 */
    categoryBtn.on('click', function(){
        if(categoryBtn.hasClass('checked')){
            closeCategoryWrapper();
        }
        else{
            showCategoryWrapper();
        }
    });

    orderBtn.on('click', function(){
        showOrderWrapper();
    });

    orderCloseBtn.on('click', function(){
        categoryBtn.removeClass('checked');
        closeOrderWrapper();
    });

    orderConfirmBtn.on('click', function(){
        OrderManager.commitOrder();
    });

    emptyOrder.on('click', function(){
        OrderManager.empty();
        closeOrderWrapper();
    });
    /* 绑定事件结束 */
})(window, document);
